package com.itheima.zixi5.XianchengTongbu.LockSuo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String cardId;
    private double money;
    //创建ReentrantLock锁对象
    private final Lock lk = new ReentrantLock();

    public Account() {
    }

    public Account(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
    public void drawMoney(double money){
String name = Thread.currentThread().getName();
lk.lock();//加锁
        try {
            if(this.money>= money){
                System.out.println(name+"取钱成功，取钱金额："+money);
                this.money -= money;
                System.out.println(name+"取钱成功，余额为："+this.money);
            }else{
                System.out.println(name+"取钱失败，余额不足");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lk.unlock();//解锁
            //以上代码为什么要用 try（）{}+catch（）{}+finally？
            //因为finally里面有解锁，解锁后其他用户才能进来运行，所以必须执行，但是try里面如果有异常，必须处理异常，
            //如果没有finally，报错可能会导致锁无法释放，其他用户无法进来

        }

    }
}
